﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Vds2465Parser
{
	internal static class GenParse_UserData_Device_Bytes
	{
		#region private constants

		private const int NrOfBytesWithDeviceByte = 3;

		#endregion private constants

		#region internal methods

		internal static byte[] GenerateBytes(byte dataType, byte device, byte[] bytes)
		{
			byte[] userDataBytes = null;

			int nrOfBytes = 0;
			if (bytes != null)
			{
				nrOfBytes = bytes.Length;
			}
			byte nrOfTotalBytes = (byte)(NrOfBytesWithDeviceByte + nrOfBytes);

			userDataBytes = new byte[nrOfTotalBytes];
			userDataBytes[0] = (byte)(nrOfTotalBytes - GenParse_UserData.HeaderLength);	// user data length
			userDataBytes[1] = dataType;
			userDataBytes[2] = device;
			if (bytes != null)
			{
				for (int index = 0; index < bytes.Length; index++)
				{
					userDataBytes[NrOfBytesWithDeviceByte + index] = bytes.ElementAt(index);
				}
			}

			return userDataBytes;
		}

		internal static bool ParseBytes(byte[] userDataBytes, byte dataType, out byte device, out byte[] bytes, out int consumedBytes)
		{
			consumedBytes = 0;
			bytes = null;
			device = 0x00;

			if (userDataBytes.Length >= NrOfBytesWithDeviceByte)
			{
				byte setLength = userDataBytes[0];
				if (userDataBytes.Length >= setLength + 2)
				{
					if (userDataBytes[0] > 0)
					{
						// first byte                
						if (userDataBytes[1] == dataType)
						{
							device = userDataBytes[2];

							byte nrOfBytes = (byte) (userDataBytes[0] - 1);	// we need to subtract the device byte
							bytes = new byte[nrOfBytes];
							for (int index = 0; index < nrOfBytes; index++)
							{
								bytes[index] = userDataBytes[NrOfBytesWithDeviceByte + index];
							}

							consumedBytes = NrOfBytesWithDeviceByte + nrOfBytes;

							return true;
						}

						// wrong value for the data type
						return false;

					}

					// TODO handle error (wrong value in first byte the length)
					return false;
				}

				// TODO handle error: not enough bytes as specified by the SL value
				return false;
			}

			// TODO handle error (not enough bytes)
			return false;
		}

		#endregion internal methods
	}
}
